#include <thread>
#include "erpc/erpc.h"
#include "spd_logger.hpp"
#include "simpost_component.hpp"
#include "module/module_name.hpp"
#include "module/module_identity.pb.h"
#include "google/protobuf/wrappers.pb.h"

class demoAPP: public simpost::Component
{
public:
    explicit demoAPP() : Component("demoAPP", "V1.0.0") {}
    virtual ~demoAPP() = default;
    bool init(void) override final;
    void exit(void) override final;
private:
    void app_task(void);
};

bool demoAPP::init(void)
{
    LOG_INFO("demoAPP init");
    std::thread app_thread([this]{ app_task(); });
    app_thread.detach();
    return true;
}

void demoAPP::exit(void)
{
    LOG_INFO("demoAPP exit");
}

void demoAPP::app_task(void)
{
    google::protobuf::Any args;
    google::protobuf::Int32Value intValue;
    google::protobuf::StringValue strValue;
    responseMessage response;

    while (true)
    {
        std::this_thread::sleep_for(std::chrono::seconds(3));
        intValue.set_value(3);
        args.PackFrom(intValue);
        response = erpc::erpc_service_call("service", MODULE_ID_AUDIO, 13, args, 5);
        if(0 != response.result())
        {
            LOG_ERROR("service {}/13 error: {}, {}", module_name(MODULE_ID_AUDIO), response.err_code(), response.err_desc());
        }
        else
        {
            response.arg().UnpackTo(&strValue);
            LOG_INFO("service moduleA/13 return: {}", strValue.value());
        }

        intValue.set_value(5);
        args.PackFrom(intValue);
        response = erpc::erpc_service_call("service", MODULE_ID_AUDIO, 10, args, 10);
        if(0 != response.result())
        {
            LOG_ERROR("service {}/10 error: {}, {}", module_name(MODULE_ID_AUDIO), response.err_code(), response.err_desc());
        }
        else
        {
            response.arg().UnpackTo(&strValue);
            LOG_INFO("service 2345/10 return: {}", strValue.value());
        }

        intValue.set_value(10);
        args.PackFrom(intValue);
        response = erpc::erpc_service_call("service", MODULE_ID_AUDIO, 15, args, 10);
        if(0 != response.result())
        {
            LOG_ERROR("service {}/15 error: {}, {}", module_name(MODULE_ID_AUDIO), response.err_code(), response.err_desc());
        }
        else
        {
            response.arg().UnpackTo(&strValue);
            LOG_INFO("service moduleA/test return: {}", strValue.value());
        }
    }
}

COMPONENT_REGISTER(demoAPP);
